﻿using System;
using System.Data;
using BLL;
using Ext.Net;
using Roles;

namespace ERP.Modules
{
    public partial class Contact : System.Web.UI.UserControl
    {
        private readonly Contact_BLL clsContact = new Contact_BLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                //BuildTree(TreePanel1.Root);
                GetData();
                GetComboBox();
                ClearTextBox();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                WindowsJob();
                WindowsVocative();
                WindowsDepartment();
                WindowsDistricts();
                WindowsProvince();
            }
        }
        //private void BuildTree(NodeCollection nodes)
        //{
        //    if (nodes == null)
        //    {
        //        nodes = new NodeCollection();
        //    }
        //    var root = new Node { Text = "Root" };
        //    nodes.Add(root);
        //    var dtContact = clsContact.BindGirdContact(string.Empty);
        //    for (var i = 0; i < dtContact.Rows.Count; i++)
        //    {
        //        var node = new Node
        //        {
        //            NodeID = dtContact.Rows[i]["Contact_ID"].ToString(),
        //            Text = dtContact.Rows[i]["Contact_Name"].ToString(),
        //            Leaf = true
        //        };
        //        root.Children.Add(node);
        //    }
        //}
        //-------Store-Datasource-----------------
        protected void StoreContact_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            GetData();
        }
        //--------Buttom-Main------------------------
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            WindowsContact.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grContact.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    GetComboBox();
                    ClearTextBox();
                    DataDetail(int.Parse(row.RecordID));
                    WindowsContact.Show();
                    sm.UpdateSelection();
                }
        }

        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grContact.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    try
                    {
                        Contact_BLL.DeleteContact(int.Parse(row.RecordID));
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetData();
        }
        //--------Buttom-Popup------------------------
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            if (txtContact_ID.Text == string.Empty)
            {
                InsertContact();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateContact();
                }
            }
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsContact.Close();
        }
        //----------Click-------------------
        protected void ContactDblClick(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            int Contact_ID = int.Parse(e.ExtraParams["Contact_ID"]);
            DataDetail(Contact_ID);
            WindowsContact.Show();
        }
        //----------Button-Windows---------------
        #region[Method]
        protected void GetData()
        {
            DataTable dtContact = clsContact.BindGirdContact(string.Empty);
            if (dtContact != null && dtContact.Rows.Count > 0)
            {
                StoreContact.DataSource = dtContact;
                StoreContact.DataBind();
            }
        }
        protected void DataDetail(int id)
        {
            DataTable dtContact = clsContact.BindGirdContactDetail(id);
            if (dtContact != null && dtContact.Rows.Count > 0)
            {
                txtContact_ID.Text = dtContact.Rows[0]["Contact_ID"].ToString();
                txtContact_Alias.Text = dtContact.Rows[0]["Contact_Alias"].ToString();
                txtContact_Name.Text = dtContact.Rows[0]["Contact_Name"].ToString();
                txtContact_Birthday.Text = dtContact.Rows[0]["Contact_Birthday"].ToString();
                chkContact_Gender.Checked = dtContact.Rows[0]["Contact_Gender"].ToString() == "Nữ";
                chkContact_Gender_Male.Checked = dtContact.Rows[0]["Contact_Gender"].ToString() == "Nam";
                cbJob.SetValue(int.Parse(dtContact.Rows[0]["Job_ID"].ToString()));
                cbVocative.SetValue(int.Parse(dtContact.Rows[0]["Contact_Vocative"].ToString()));
                cbDepartment.SetValue(int.Parse(dtContact.Rows[0]["Department_ID"].ToString()));
                txtContact_Phone.Text = dtContact.Rows[0]["Contact_Phone"].ToString();
                txtContact_MobilePhone.Text = dtContact.Rows[0]["Contact_MobilePhone"].ToString();
                txtContact_Email.Text = dtContact.Rows[0]["Contact_Email"].ToString();
                txtContact_Address.Text = dtContact.Rows[0]["Contact_Address"].ToString();
                //cbProvince.SetValue(dtContact.Rows[0]["Job_ID"].ToString());
                cbDistricts.SetValue(int.Parse(dtContact.Rows[0]["District_ID"].ToString()));  
                txtContact_Note.Text = dtContact.Rows[0]["Contact_Note"].ToString();
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            var Contact = new Contact_BLL();
            var dtContact = Contact.BindGirdContact(string.Empty);
            if (dtContact != null && dtContact.Rows.Count > 0)
            {
                foreach (DataRow dr in dtContact.Rows)
                {
                    if (txtContact_ID.Text != dr["Contact_ID"].ToString())
                    {
                        if (txtContact_Alias.Text == dr["Contact_Alias"].ToString())
                        {
                            kiemtra = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã người liên hệ đã tồn tại !");
                        }
                        else if (txtContact_Name.Text == dr["Contact_Name"].ToString())
                        {
                            kiemtra = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Tên người liên hệ đã tồn tại !");
                        }
                    }
                }
            }
            return kiemtra;
        }
        protected void InsertContact()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new ET.Contact_ET
                    {
                        Contact_Alias = txtContact_Alias.Text,
                        Contact_Name = txtContact_Name.Text,
                        Contact_BirthDay = DateTime.Parse(txtContact_Birthday.Text),
                        Contact_Gender = chkContact_Gender.Checked ? "Nữ" : "Nam",
                        Job_ID = int.Parse(cbJob.SelectedItem.Value),
                        Contact_Vocative = int.Parse(cbVocative.SelectedItem.Value),
                        Department_ID = int.Parse(cbDepartment.SelectedItem.Value),
                        Contact_Phone = txtContact_Phone.Text,
                        Contact_MobilePhone = txtContact_MobilePhone.Text,
                        Contact_Email = txtContact_Email.Text,
                        Contact_Address = txtContact_Address.Text,
                        District_ID = int.Parse(cbDistricts.SelectedItem.Value),
                        Contact_Note = txtContact_Note.Text,
                        Contact_Date_Add = DateTime.Now,
                        Contact_Computer_Add = Environment.MachineName
                    };
                    Contact_BLL.InsertContact(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                    GetData();
                    GetComboBox();
                    ClearTextBox();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }
        protected void UpdateContact()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new ET.Contact_ET
                    {
                        Contact_ID = int.Parse(txtContact_ID.Text),
                        Contact_Alias = txtContact_Alias.Text,
                        Contact_Name = txtContact_Name.Text,
                        Contact_BirthDay = DateTime.Parse(txtContact_Birthday.Text),
                        Contact_Gender = chkContact_Gender.Checked ? "Nữ" : "Nam",
                        Job_ID = int.Parse(cbJob.SelectedItem.Value),
                        Contact_Vocative = int.Parse(cbVocative.SelectedItem.Value),
                        Department_ID = int.Parse(cbDepartment.SelectedItem.Value),
                        Contact_Phone = txtContact_Phone.Text,
                        Contact_MobilePhone = txtContact_MobilePhone.Text,
                        Contact_Email = txtContact_Email.Text,
                        Contact_Address = txtContact_Address.Text,
                        District_ID = int.Parse(cbDistricts.SelectedItem.Value),
                        Contact_Note = txtContact_Note.Text,
                        Contact_Date_Modify = DateTime.Now,
                        Contact_Computer_Modify = Environment.MachineName
                    };
                    Contact_BLL.UpdateContact(obj);
                    WindowsContact.Close();
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Sữa thành công!");
                    GetData();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }
        #endregion
        #region [ComboBox]
        protected void GetComboBox()
        {
            var clsJob = new Job_BLL();
            DataTable dtJob = clsJob.BindGirdtb_Job(string.Empty);
            if (dtJob != null && dtJob.Rows.Count > 0)
            {
                JobStore.DataSource = dtJob;
                JobStore.DataBind();
            }

            var clsVocative = new Vocative_BLL();
            DataTable dtVocative = clsVocative.BindGirdtb_Vocative(string.Empty);
            if (dtVocative != null && dtVocative.Rows.Count > 0)
            {
                VocativeStore.DataSource = dtVocative;
                VocativeStore.DataBind();
            }

            var clsDepartment = new Department_BLL();
            DataTable dtDepartment = clsDepartment.BindGirdtb_Department(string.Empty);
            if (dtDepartment != null && dtDepartment.Rows.Count > 0)
            {
                DepartmentStore.DataSource = dtDepartment;
                DepartmentStore.DataBind();
            }

            var clsProvince = new Province_BLL();
            DataTable dtProvince = clsProvince.BindGirdProvince(string.Empty);
            if (dtProvince != null && dtProvince.Rows.Count > 0)
            {
                ProvinceStore.DataSource = dtProvince;
                ProvinceStore.DataBind();
            }

            var clsDistricts = new Districts_BLL();
            DataTable dtDistricts = clsDistricts.BindGirdDistricts(string.Empty);
            if (dtDistricts != null && dtDistricts.Rows.Count > 0)
            {
                DistrictsStore.DataSource = dtDistricts;
                DistrictsStore.DataBind();
            }
        }
        protected void ProvinceSelectIndex_Change(object sender, StoreReadDataEventArgs e)
        {
            cbDistricts.ReadOnly = false;
            var clsDistricts = new Districts_BLL();
            if (cbProvince.SelectedItem.Value != null)
            {
                var dtDistricts = clsDistricts.BindGirdDistricts_Province(int.Parse(cbProvince.SelectedItem.Value));
                if (dtDistricts != null && dtDistricts.Rows.Count > 0)
                {
                    DistrictsStore.DataSource = dtDistricts;
                    DistrictsStore.DataBind();
                }
                else
                {
                    cbProvince.Clear();
                    cbDistricts.ReadOnly = true;
                    HTML.clsFormat.Alert_INFO("Thông báo", "Tỉnh này chưa có quận huyện vui lòng chọn tỉnh khác !");
                }
            }
            else
            {
                cbProvince.Clear();
                cbDistricts.ReadOnly = true;
                HTML.clsFormat.Alert_INFO("Thông báo", "Vui lòng chọn tỉnh !");
            }
        }
        protected void ReloadComboBox(object sender, StoreReadDataEventArgs e)
        {
            GetComboBox();
        }
        #endregion
        #region[ClearTextbox]
        protected void ClearTextBox()
        {
            FormPanelContact.Reset();

            txtContact_ID.Text = string.Empty;
            txtContact_Alias.Text = MaTuDong();
            txtContact_Name.Text = string.Empty;
            txtContact_Birthday.Text = string.Empty;
            txtContact_Phone.Text = string.Empty;
            txtContact_MobilePhone.Text = string.Empty;
            txtContact_Email.Text = string.Empty;
            txtContact_Address.Text = string.Empty;
            txtContact_Note.Text = string.Empty;

            chkContact_Gender.Checked = false;
            cbJob.Clear();
            cbVocative.Clear();
            cbDepartment.Clear();
            cbProvince.Clear();
            cbDistricts.Clear();
            cbDistricts.ReadOnly = true;
        }
        #endregion
        #region[MaTangTuDong]
        protected string MaTuDong()
        {
            int i;
            DataTable dt = clsContact.BindGirdContact(string.Empty);
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = int.Parse(dt.Rows[0]["Contact_ID"].ToString());
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["Contact_ID"].ToString()) > max)
                    {
                        max = int.Parse(dt.Rows[i]["Contact_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            else
            {
                i = 0;
            }
            return "NLH_00" + i;
        }
        #endregion
        #region[Search]
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            DataTable dtContact = clsContact.BindGirdContact(txtSearch.Text);
            if (dtContact != null && dtContact.Rows.Count > 0)
            {
                StoreContact.DataSource = dtContact;
                StoreContact.DataBind();
            }
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Contact, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelContact.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Contact, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion

        private void WindowsJob()
        {
            Window win = new Window()
            {
                ID = "WindowsJob",
                Title = "Chức vụ",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Job.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsVocative()
        {
            Window win = new Window()
            {
                ID = "WindowsVocative",
                Title = "Danh xưng",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Vocative.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsDepartment()
        {
            Window win = new Window()
            {
                ID = "WindowsDepartment",
                Title = "Phòng ban",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Department.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsDistricts()
        {
            Window win = new Window()
            {
                ID = "WindowsDistricts",
                Title = "Quận huyện",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Districts.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsProvince()
        {
            Window win = new Window()
            {
                ID = "WindowsProvince",
                Title = "Tỉnh",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Province.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
    }
}